#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update, COOPGIS_FormMisc, COOPGIS_FormGeography, COOPGIS_FormAssembly
import os, csv, shutil, datetime, time, reportlab, djangoproject.settings, random
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
import djangoproject.settings
import _mysql as mysql
from models import *
from django import forms

def Viewer(request, StationOverride=None):
    ApplicationName=djangoproject.settings.COOPGISViewerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap)
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    SelectionStation, SelectionSpan, GPSStatus = COOPGIS_FormGeography.SetSelectionStationAndSpan(form)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByOldMapNumber(form, SelectionStation, SelectionSpan)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByRoad(form, SelectionStation, SelectionSpan)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByMeter(form, SelectionStation, SelectionSpan)
    if(StationOverride and not SelectionStation and not SelectionSpan):
        try:
            SelectionStation=djangoproject.models.geography.Station.objects.filter(id=StationOverride)[0]
        except:
            pass

    if(not SelectionStation and not SelectionSpan):
        Zoom=21
    else:
        Zoom=21
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, Zoom=Zoom)
    Longitude, Latitude = COOPGIS_Ajax.GetLatitudeLongitude(SelectionStation, SelectionSpan, SRID=djangoproject.settings.COOPGISGPSSRID)
    Longitude=abs(Longitude)
    Latitude=abs(Latitude)
    if(SelectionStation):
        County=GetCounty(SelectionStation)
    elif(SelectionSpan):
        County=GetCounty(SelectionSpan.StartStation)
    else:
        County='Unknown'
    
    CurrentGridSquareName, MapNumbersWithStation, MapNumbersWithStationAndMap=COOPGIS_FormGeography.GetGridInfo(form, SelectionStation)
    StationAssemblyList, SpanAssemblyList = COOPGIS_Misc.GetNearbyInfo(SelectionStation, SelectionSpan)
    MapFileName, LayerName =COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress) 

    OpenLayersJavaScriptHeading=COOPGIS_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPGIS_Ajax.GetOpenLayersJavaScript(OpenLayersZoom, MapFileName, LayerName, OpenLayersJavaScriptHeading)

    COOPGIS_Misc.UpdateSelection(SelectionStation, SelectionSpan, UserNameOrIPAddress)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/viewer.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form,
                 'StationAssemblyList': StationAssemblyList, 'SpanAssemblyList': SpanAssemblyList,
                 'Longitude': Longitude, 'Latitude': Latitude,
                 'County': County, 'MapNumbersWithStation': MapNumbersWithStation,
                 'CurrentGridSquareName':CurrentGridSquareName,
                 'MapNumbersWithStationAndMap':MapNumbersWithStationAndMap,
                 'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading, 'MapFileName': MapFileName})
    return HttpResponse(t.render(c))


def Printer(request, StationOverride=None):
    ApplicationName=djangoproject.settings.COOPGISViewerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName, DefaultMap)
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    SelectionStation, SelectionSpan, GPSStatus = COOPGIS_FormGeography.SetSelectionStationAndSpan(form)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByOldMapNumber(form, SelectionStation, SelectionSpan)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByRoad(form, SelectionStation, SelectionSpan)
    SelectionStation, SelectionSpan = COOPGIS_FormGeography.SetSelectionStationAndSpanByMeter(form, SelectionStation, SelectionSpan)
    if(StationOverride and not SelectionStation and not SelectionSpan):
        try:
            SelectionStation=djangoproject.models.geography.Station.objects.filter(id=StationOverride)[0]
        except:
            pass

    if(not SelectionStation and not SelectionSpan):
        Zoom=15
    else:
        Zoom=23
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, Zoom=Zoom)
    Longitude, Latitude = COOPGIS_Ajax.GetLatitudeLongitude(SelectionStation, SelectionSpan, SRID=djangoproject.settings.COOPGISGPSSRID)
    Longitude=abs(Longitude)
    Latitude=abs(Latitude)
    if(SelectionStation):
        County=GetCounty(SelectionStation)
    elif(SelectionSpan):
        County=GetCounty(SelectionSpan.StartStation)
    else:
        County='Unknown'
    
    CurrentGridSquareName, MapNumbersWithStation, MapNumbersWithStationAndMap=COOPGIS_FormGeography.GetGridInfo(form, SelectionStation)
    StationAssemblyList, SpanAssemblyList = COOPGIS_Misc.GetNearbyInfo(SelectionStation, SelectionSpan)
    MapFileName, LayerName =COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress) 

    OpenLayersJavaScriptHeading=COOPGIS_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPGIS_Ajax.GetOpenLayersJavaScript(OpenLayersZoom, MapFileName, LayerName, OpenLayersJavaScriptHeading)

    COOPGIS_Misc.UpdateSelection(SelectionStation, SelectionSpan, UserNameOrIPAddress)
    t = loader.get_template('/opt/coopgis/djangoproject/templates/printer.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form,
                 'StationAssemblyList': StationAssemblyList, 'SpanAssemblyList': SpanAssemblyList,
                 'Longitude': Longitude, 'Latitude': Latitude,
                 'County': County, 'MapNumbersWithStation': MapNumbersWithStation,
                 'CurrentGridSquareName':CurrentGridSquareName,
                 'MapNumbersWithStationAndMap':MapNumbersWithStationAndMap,
                 'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading, 'MapFileName': MapFileName})
    return HttpResponse(t.render(c))




def AssetViewer(request):
    ApplicationName=djangoproject.settings.COOPGISViewerApplicationName
    UserNameOrIPAddress, DefaultMap=COOPGIS_Misc.GetUserNameOrIPAddress(request, GetDefaultMap=True, ApplicationName=ApplicationName)
    form=COOPGIS_FormMisc.BuildForm(request, ApplicationName + 'Asset', DefaultMap)
    COOPGIS_FormGeography.GetAndSetDefaultMap(form, ApplicationName, UserNameOrIPAddress)
    SelectionStation = None
    SelectionSpan = None
    if(not SelectionStation and not SelectionSpan):
        Zoom=15
    else:
        Zoom=23
    OpenLayersZoom=COOPGIS_Ajax.GetOpenLayersZoom(SelectionStation, SelectionSpan, Zoom=Zoom)
    Longitude, Latitude = COOPGIS_Ajax.GetLatitudeLongitude(SelectionStation, SelectionSpan, SRID=djangoproject.settings.COOPGISGPSSRID)
    Longitude=abs(Longitude)
    Latitude=abs(Latitude)
    MapFileName, LayerName =COOPGIS_Misc.GenerateDynamicMapFile(ApplicationName, UserNameOrIPAddress) 

    OpenLayersJavaScriptHeading=COOPGIS_Ajax.GetOpenLayersJavaScriptHeading()
    OpenLayersJavaScript=COOPGIS_Ajax.GetOpenLayersJavaScript(OpenLayersZoom, MapFileName, LayerName, OpenLayersJavaScriptHeading)
    form=COOPGIS_FormAssembly.ProcessAssetViewerForm(form, UserNameOrIPAddress)
    form=COOPGIS_FormAssembly.PopulateAssetViewerForm(form)
    StationCompatibleUnitOneName=Station.objects.all().order_by('id')[0].CompatibleUnitOneName
    StationCompatibleUnitTwoName=Station.objects.all().order_by('id')[0].CompatibleUnitTwoName
    SpanCompatibleUnitOneName=Span.objects.all().order_by('id')[0].CompatibleUnitOneName
    SpanCompatibleUnitTwoName=Span.objects.all().order_by('id')[0].CompatibleUnitTwoName
    StationsMatchingOne=Station.objects.filter(CompatibleUnitOneName=StationCompatibleUnitOneName).count()
    StationsMatchingTwo=Station.objects.filter(CompatibleUnitTwoName=StationCompatibleUnitTwoName).count()
    SpansMatchingOne=Span.objects.filter(CompatibleUnitOneName=SpanCompatibleUnitOneName).count()
    SpansMatchingTwo=Span.objects.filter(CompatibleUnitTwoName=SpanCompatibleUnitTwoName).count()
    NumberOfStations=Station.objects.all().count()
    NumberOfSpans=Span.objects.all().count()



    t = loader.get_template('/opt/coopgis/djangoproject/templates/assetviewer.html')
    c = Context({'OpenLayersZoom': OpenLayersZoom, 'form': form,
                 'Longitude': Longitude, 'Latitude': Latitude,
                 'OpenLayersJavaScript': OpenLayersJavaScript,
                 'OpenLayersJavaScriptHeading': OpenLayersJavaScriptHeading, 'MapFileName': MapFileName,
                 'StationCompatibleUnitOneName': StationCompatibleUnitOneName, 'StationCompatibleUnitTwoName': StationCompatibleUnitTwoName,
                 'SpanCompatibleUnitOneName': SpanCompatibleUnitOneName, 'SpanCompatibleUnitTwoName': SpanCompatibleUnitTwoName,
                 'StationsMatchingOne': StationsMatchingOne, 'StationsMatchingTwo': StationsMatchingTwo, 'SpansMatchingOne': SpansMatchingOne, 
                 'SpansMatchingTwo': SpansMatchingTwo, 'NumberOfStations': NumberOfStations, 'NumberOfSpans': NumberOfSpans})
    return HttpResponse(t.render(c))



def GetCounty(station):
    try:
        county=County.objects.filter(Border__contains=station.Point)[0]
        return county.Name
    except:
        return 'Unknown'



